//
//  AppUserTool.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/25.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

let tokenKey: String = "token.ExtremeHealth"

struct AppUserTool {

    static func save(_ tokenInfo: TokenInfo) {
        let def = UserDefaults.standard
        do {
            let data = try PropertyListEncoder().encode(tokenInfo)
            def.set(data, forKey: tokenKey)
            def.synchronize()
        } catch {
            debugPrint(error.localizedDescription)
        }
    }

    static func fetch() -> TokenInfo {
        let def = UserDefaults.standard
        guard let data = def.value(forKey: tokenKey) as? Data else {
            debugPrint("no token info saved")
            return TokenInfo(accessToken: "", refreshToken: "")
        }
        do {
            let tokenInfo = try PropertyListDecoder().decode(TokenInfo.self, from: data)
            return tokenInfo
        } catch {
            debugPrint(error.localizedDescription)
            return TokenInfo(accessToken: "", refreshToken: "")
        }
    }

}
